package com.china.springServer.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinTaskExample extends RecursiveTask<Integer> {

    public static final int threadHold = 2;
    private final int start;
    private final int end;


    public ForkJoinTaskExample(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;

        boolean canCompute = (end - start) <= threadHold;
        if (canCompute) {
            // 任务足够小，不再进行拆分
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            // 任务大于阈值，则拆分成两个字任务进行计算
            int middle = (end + start) / 2;
            ForkJoinTaskExample left = new ForkJoinTaskExample(start, middle);
            ForkJoinTaskExample right = new ForkJoinTaskExample(middle + 1, end);

            // 执行子任务
            left.fork();
            right.fork();

            // 等待子任务执行合并结果
            Integer leftResult = left.join();
            Integer rightResult = right.join();

            sum = leftResult + rightResult;
        }
        return sum;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ForkJoinPool forkJoinPool = new ForkJoinPool();

        ForkJoinTaskExample task = new ForkJoinTaskExample(1, 10000);

        ForkJoinTask<Integer> result = forkJoinPool.submit(task);

        System.out.println(result.get());
    }
}
